<?php

namespace app\controller;

use app\BaseController;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;

class User extends Common
{

    // http://www.penyou.com/User/info
    public function info()
    {
        $userInfo = Db::name('users')->field('id,phone,time_reg,vip_time')->where(array('id' => $this->userId,'is_delete'=>0))->find();



        singleJson($userInfo, '用户异常');
    }

    // http://www.penyou.com/User/exchangeCode
    public function exchangeCode()
    {
        $code = Request::param('code');
        if(empty($code)){
            singleJson($code, '请输入兑换码');
        }
        $cdkeyInfo = Db::name('cdkey')->field('id,title,duration')->where("code= '".$code."' AND status != 2 AND is_delete = 0")->find();
     //   echo Db::name('cdkey')->getlastsql();
        if(empty($cdkeyInfo)){
            singleJson($cdkeyInfo, '该兑换码不存在或已使用');
        }

        $userInfo = Db::name('users')->field('id,vip_time')->where(array('id' => $this->userId,'is_delete'=>0))->find();
        $vipTime = strtotime($userInfo['vip_time']) > time() ? strtotime($userInfo['vip_time']) : time();
        $vipDate = date("Y-m-d",$vipTime+$cdkeyInfo['duration']);
       $rs = Db::name('users')->where(array('id' => $this->userId))->save(array('vip_time'=> $vipDate));
       if($rs){
           Db::name('cdkey')->where("id= '".$cdkeyInfo['id']."'")->save(array('status'=> 2,'use_uid'=>$this->userId,'use_date'=>date('Y-m-d')));
           singleJson(array('vipDate'=>$vipDate,'tip'=>'兑换'.$cdkeyInfo['title'].'成功'));
           return;
       }
        singleJson(false, '兑换失败');

    }


}
